<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class Admin_PrivilegeController extends Zend_Controller_Action
{

    private $_privilegeService;

	public function init()
    {
        $this->_privilegeService = $this->_helper->getService('Core_Service_Privilege');
    }

    public function indexAction()
    {
        // Throw an exception if the user is not allowed to fetch privileges
        $this->_helper->acl->isAllowed('service:privilege', 'fetch');
        
        $groupService = $this->_helper->getService('Core_Service_Group');
        $this->view->groups = $groupService->fetchAll();
    }
    
    public function editAction()
    {
        $this->_helper->acl->isAllowed('service:privilege', 'save');

        $groupId = $this->_getParam('group');

        $validator = new Zend_Validate_Int();
        if (!$validator->isValid($groupId)) {
        	throw new RedCross_Exception_ValidationFailed();
        }
        $groupId = (int) $groupId;

        $form = new Admin_Form_Privilege_Privileges();

        // Fill the form with privileges
        $resources = $this->_privilegeService->fetchAllResourcesWithPrivileges();
        $form->fillForm($resources);
        $this->view->resources = $resources;

        $request = $this->getRequest();
        if ($request->isPost() && $form->isValid($request->getPost())) {
        	$this->_privilegeService->savePrivileges($groupId, $form->getValues());
            $this->view->successfulUpdate = true;
        }

        // Populate the form with values from the database
        $privileges = $this->_privilegeService->fetchAllByGroup($groupId);
        $allPrivileges = $this->_privilegeService->fetchAll();
        $this->view->privileges = $allPrivileges;

        $groupService = $this->_helper->getService('Core_Service_Group');
        $this->view->group = $groupService->fetchGroupNameById($groupId);

        $form->populateForm($privileges);
        $this->view->form = $form;
    }

}